package com.atguigu.gulimall.member.interceptor;
import com.alibaba.fastjson.JSON;
import com.atguigu.common.vo.LoginRespEntity;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Classname LoginUserInterceptor
 * @Description TODO
 * @Date 2021/10/13 21:08
 * @Author Anonymous
 */
@SuppressWarnings("all")
@Component
public class LoginUserInterceptor implements HandlerInterceptor {

    public static ThreadLocal<LoginRespEntity> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        // 这个请求直接放行
        boolean match = new AntPathMatcher().match("/member/**", uri);
        if (match) {
            return true;
        }
        HttpSession session = request.getSession();
        //得到当前登录的用户
//        Object user = session.getAttribute("loginUser");
//        LoginRespEntity loginUser = new ObjectMapper().convertValue(user, LoginRespEntity.class);
//        LoginRespEntity loginUser = JSON.parseObject(JSON.toJSONString(user), LoginRespEntity.class);
//        System.out.println("user============" + user);

        LoginRespEntity loginUser = (LoginRespEntity) session.getAttribute("loginUser");

        if (loginUser == null) {
            //说明没有登录,跳转到登录页
            request.getSession().setAttribute("msg", "请登录");
            response.sendRedirect("http://auth.gulimall.com/login.html");
            return false;
        } else {
            //如果已经登录就放入ThreadLocal，以后其它线程都可以访问到，也就是访问其他的服务都可以用
            threadLocal.set(loginUser);
            return true;
        }
    }
}
